
package com.be.beadmin.device.impl;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.entity.*;
import com.be.beadmin.device.repository.ToolInfoRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.ToolFileMapperEx;
import com.be.beadmin.device.repository.ToolFileRepository;
import com.be.beadmin.device.service.ToolFileService;
import com.be.beadmin.device.dto.input.ToolFileDto;
import com.be.beadmin.device.dto.output.ToolFileEx;
import com.be.beadmin.device.dto.input.ToolFileQueryCriteria;
import com.be.beadmin.device.mapper.ToolFileMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @description 服务实现
* @author sly
* @date 2023-10-18
**/
@Service
@RequiredArgsConstructor
public class ToolFileServiceImpl implements ToolFileService {

    @Autowired
    private  ToolFileRepository toolFileRepository;
    @Autowired
    private ToolInfoRepository toolInfoRepository;
    @Resource
    private  ToolFileMapper toolFileMapper;
    @Resource
    private  ToolFileMapperEx toolFileExMapper;
    @Resource
    private SerialNumberService serialNumberService;

    MinioUtil minioUtil = new MinioUtil();

    @Override
    public Page<ToolFileEx> getToolFileByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<ToolFile> page = toolFileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(ToolFile_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(ToolFile_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<ToolFileEx> page1 = page.map(toolFileExMapper::toEntity);
            return page1;

    }

    @Override
    public void addToolFile(ToolFileDto toolFileDto) {
            ToolFile result = toolFileRepository.findToolFileByIdAndDelete(toolFileDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("ToolFile不存在,请重新查询");
            }
            ToolFile toolFile = toolFileMapper.toEntity(toolFileDto);
            toolFileRepository.save(toolFile);
    }

    @Override
    public void updateToolFile(ToolFileDto toolFileDto) {
            ToolFile toolFile = toolFileRepository.findToolFileById(toolFileDto.getId());
            toolFile = toolFileMapper.toEntity(toolFileDto);
            toolFileRepository.save(toolFile);
    }


    @Override
    public void delToolFile(String id) {
        ToolFile toolFile = toolFileRepository.findToolFileById(id);
        toolFile.setDelete(1);
        toolFileRepository.save(toolFile);
    }

    @Override
    public void delToolFiles (List<String> ids) { }

    @Override
    public void uploadToolFile(String toolinfoId, MultipartFile[] multipartFiles, String fileName, String memo, String bucketName) throws Exception {
        ToolInfo toolInfo = toolInfoRepository.findToolInfoById(toolinfoId);
        //对文件进行操作
        for(MultipartFile multipartFile:multipartFiles) {
            ToolFile toolFile = new ToolFile();
//        //文件名
//        if (fileName==null||fileName.equals("")) {
//            fileName = multipartFile.getOriginalFilename();
//        }
            fileName=multipartFile.getOriginalFilename();
            toolFile.setFileName(fileName);

            //判断同一个项目是否有相同的文件名
            int f = toolFileRepository.countToolFilesByFileNameAndToolNameAndDelete(fileName, toolInfo.getToolName(), 0);

            //文件后缀
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            toolFile.setFileExtEndDate(ext);

            String version;
            while (true) {
                version = "v1." + f;
                int num = toolFileRepository.countToolFilesByFileNameAndVersionAndDelete(fileName, version, 0);
                if (num == 0) {
                    break;
                } else {
                    f++;
                }
            }
            toolFile.setVersion(version);

            //文件大小
            BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
            toolFile.setFileSize(fileSize);
            //流水号
            String fileCode = serialNumberService.getNextSnByCode("FileCode");
            toolFile.setFileCode(fileCode);
            //项目id
            toolFile.setToolinfoId(toolinfoId);
            //项目名称
            toolFile.setToolName(toolInfo.getToolName());
            //检查单号
            toolFile.setToolId(toolInfo.getToolId());
            //备注
            toolFile.setMemo(memo);
            //设置bucketName
            toolFile.setBucketName(bucketName);
            //处理文件

            String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + version + "." + ext;
            String fileUrl = minioUtil.uploadFile3(multipartFile, bucketName, newFileName);
            toolFile.setFileUrl(fileUrl);
            toolFile.setNewFileName(newFileName);
            toolFileRepository.save(toolFile);
        }

    }
}